<?php
/**
 * Created by PhpStorm.
 * User: majiawen
 * Date: 2018/2/25
 * Time: 9:34
 */

namespace app\admin\controller\v1;


use app\admin\controller\Fun;
use think\Db;

/**
 * @title 后台-捎货管理-捎货人管理-捎货人考试管理-V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class ShaohuoProblem extends Base
{
    /**
     * @title 成为捎货人考试题目查询列表
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoProblem desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:shaohuoProblemList desc:捎货题目列表
     *
     * @param name:page type:string require:1 default: other: desc:页码
     * @param name:page_size type:string require:1 default: other: desc:每页个数
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     *
     * @return data:[]
     */
    public function shaohuoProblemList()
    {
        $where['status'] = ['<>',\app\common\Model\ShaohuoProblem::STATUS_DELETE];
        //查询
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['title'] = ['like', '%' . $search . '%'];
        }

        $ShaohuoProblem = new \app\common\Model\ShaohuoProblem();
        if(isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'],$ShaohuoProblem->sort_field)){
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        }else{
            $order = ['create_time'=> $this->sort_type[0] ];
        }

        $list = Db::name('shaohuo_problem')
            ->where($where)
            ->order($order)
//            ->field('fc_id id,func_name name')
            ->paginate($this->page_size,false,['page'=>$this->param['page']]);
//        var_dump($model->_type);die;
        if ($list) {
            $data = $list->items();
            $response = [];
            foreach ($data as $key => $model) {
                $far = explode('|', $model['options']);
                $options = [];
                foreach ($far as $_k => $_v) {
                    $item = [];
                    $item['description'] = self::num2letter($_k + 1) . '：' .$_v;
                    $item['isAnswer'] = self::number2pos($model['answer'], $_k + 1);
                    array_push($options, $item);
                }
                $response[] = ['sp_id' => $model['sp_id'],
                    'title' => $model['title'],
                    'type' => $ShaohuoProblem->_type[$model['type']],
                    '_type' => $model['type'],
                    'options' => $options,
                    'answer' => self::num2letter(self::number2pos($model['answer'])),
                    'create_time' => $model['create_time'],
                    'status' => $ShaohuoProblem->_status[$model['status']]
                ];
            }
            return Fun::success(['list' => $response, 'total_num' => $list->total()]);
        } else {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 添加新捎货试题
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoProblem desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:addShaohuoProblem desc:
     *
     * @param name:title type:string require:1 default: other:1<? desc:题目名称
     * @param name:type type:string require:1 default: other:1 desc:题目类型:0为单选,1为多选
     * @param name:options type:string require:1 default: other:A:1|B:2|C:3 desc:题目选项,多个选项以|隔开
     * @param name:answer type:string require:1 default: other:2|3 desc:题目答案,多个选项以|隔开
     *
     * @return data:[]
     */
    public function addShaohuoProblem()
    {
        if (empty($this->param['title'])||empty($this->param['options'])||empty($this->param['answer'])){
            return Fun::error('');//TODO 无数据，定义错误类型
        }


        $answer = explode('|',trim($this->param['answer'],'|'));
        $num = 0;
        foreach ($answer as $k => $v){
            $num += self::pos2number($v);
        }

        $data = [
            'title' => $this->param['title'] ,
            'type' => intval($this->param['type']) ,
            'options' => $this->param['options'] ,
            'answer' => $num ,
        ];
        $res = Db::name('shaohuo_problem')
            ->insert($data);
        if ($res) {
            return Fun::success('操作成功');
        } else {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 修改捎货试题的内容
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoProblem desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:alterShaohuoProblem desc:
     *
     * @param name:sp_id type:string require:1 default: other:1 desc:题目ID
     * @param name:title type:string require:1 default: other:1<? desc:题目名称
     * @param name:type type:string require:1 default: other:1 desc:题目类型:0为单选,1为多选
     * @param name:options type:string require:1 default: other:A:1|B:2|C:3 desc:题目选项,多个选项以|隔开
     * @param name:answer type:string require:1 default: other:2|3 desc:题目答案,多个选项以|隔开
     *
     * @return data:[]
     */
    public function alterShaohuoProblem()
    {
        if (empty($this->param['sp_id'])||empty($this->param['title'])||empty($this->param['options'])||empty($this->param['answer'])){
            return Fun::error('');//TODO 无数据，定义错误类型
        }


        $answer = explode('|',trim($this->param['answer'],'|'));
        $num = 0;
        foreach ($answer as $k => $v){
            $num += self::pos2number($v);
        }

        $data = [
            'sp_id' => $this->param['sp_id'] ,
            'title' => $this->param['title'] ,
            'type' => intval($this->param['type']) ,
            'options' => $this->param['options'] ,
            'answer' => $num ,
        ];
        $res = Db::name('shaohuo_problem')
            ->update($data);
        if ($res) {
            return Fun::success('操作成功');
        } else {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 修改捎货试题状态
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoProblem desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:alterShaohuoProblemStatus desc:
     *
     * @param name:ids type:string require:1 default:1,2,3 other: desc:题目ID,以逗号拼接
     * @param name:status type:string require:1 default: other:1 desc:状态:0为禁用,1为有效,2为删除
     *
     * @return data:[]
     */
    public function alterShaohuoProblemStatus()
    {
        if (empty($this->param['ids'])){
            return Fun::error('');//TODO 无数据，定义错误类型
        }


        $ids = explode(',',trim($this->param['ids'],','));

        $data = [
            'status' => intval($this->param['status']) ,
        ];
        $res = Db::name('shaohuo_problem')
            ->where('sp_id','in',$ids)
            ->update($data);
        if ($res) {
            return Fun::success('操作成功');
        } else {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
    }

    /**
     * 对应选项数字为字母
     */
    protected function num2letter($num){
        $letter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $res = '';
        if (is_array($num)) {
            foreach ($num as $key => $value) {
                $res .= $letter[$value - 1];
            }
        } else {
            $res = $letter[$num - 1];
        }

        return $res;
    }

    /**
     * 十进制数字转换返回所有(特定)置位位置
     * @param $number
     * @param int $pos
     * @return array|int
     */
    protected function number2pos($number, $pos = 0)
    {
        if ($pos) {
            return ($number >> ($pos - 1)) & 1;
        }
        $result = array();
        $bin = decbin($number);
        $count = strlen($bin);
        for ($i = 1; $i <= $count; $i++) {
            if (($number >> ($i - 1)) & 1) {
                //if (!empty($pos) && !in_array($i, $pos)) continue;
                $result[] = $i;
            }
        }
        return $result;
    }
    /**
     * 根据置位位置数组转换成十进制
     * @param $pos int|array 置位位置(数组)
     * @param int $number 原始十进制
     * @return int 十进制数字,用于存到数据库
     * @example pos2number(array(1,2))=>3,pos2number(array(1,2),10)=>11
     */
    protected static function pos2number($pos, $number = 0)
    {
        $posArray = is_array($pos) ? $pos : array($pos);
        $count = count($posArray);
        for ($i = 0; $i < $count; $i++) {
            $number |= (1 << (intval($posArray[$i]) - 1));
        }
        return $number;
    }
}